<% add_decidim_page_title(t(".title")) %>
<%= append_stylesheet_pack_tag "participatory_texts_admin" %>

<div class="item_show__header">
  <h1 class="item_show__header-title">
    <%= t(".title") %>
    <%= render partial: "bulk-actions" %>
  </h1>
</div>
<% if @drafts.any? %>
  <div class="item__edit item__edit-1col">
    <div class="item__edit-form">
      <%= decidim_form_for(@preview_form, url: participatory_texts_path, html: { class: "form-defaults form grid-container" }) do |form| %>
        <div class="form__wrapper">
          <div class="card">
            <div class="row column">
              <p class="mt-3"><%= t(".info_1") %></p>
              <ul id="participatory-text" class="draggable-list js-connect js-list-actives mt-2.5 ml-2.5 mr-2.5"
                  data-controller="accordion"
                  data-sort-url="#"
                  data-multi-expand="true"
                  data-allow-all-closed="true">
                <%= form.fields_for(:proposals) do |prop_form| %>
                  <% proposal = @drafts[prop_form.index] %>

                  <li class="draggable-content is-active" data-accordion-item draggable="true">
                    <a data-open="true" data-controls="article-<%= proposal.id %>">
                      <%= icon "arrow-right-s-line" %>
                      <%= preview_participatory_text_section_title(proposal) %>
                      <span><%= icon "menu-line", class: "fill-black" %></span>
                    </a>
                    <div data-tab-content id="article-<%= proposal.id %>">
                      <%= render "article-preview", { form: prop_form, proposal: } %>
                    </div>
                  </li>
                <% end %>
              </ul>
            </div>
          </div>
        </div>
        <div class="item__edit-sticky">
          <div class="item__edit-sticky-container">
            <%= form.submit t(".save_draft"), name: :save_draft, class: "button button__sm button__secondary" %>
            <%= form.submit t(".publish_document"), class: "button button__sm button__secondary" %>
          </div>
        </div>
      <% end -%>
    </div>
  </div>
<% end %>
<script>
  $(window).on("load", function() {
    // Not all browsers submit the buttons as form data.
    $("button[name=\"save_draft\"]").on("click", function(ev) {
      ev.preventDefault();

      var $form = $(this).parents("form");
      $form.append("<input type=\"hidden\" name=\"save_draft\" value=\"true\" />");
      $form.submit();
    });
    $("#participatory-text").on("sortupdate",
      function(event, ui) {
        $("#participatory-text li").each(function(idx, li) {
          input = $(li).find("input.position").val(idx + 1);
        });
      }
    );
  });
</script>
